package li.com.springaidemo.controller;

import cn.hutool.core.img.Img;
import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.DeleteObjectsRequest;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.servlet.ServletException;
import jakarta.websocket.server.PathParam;
import li.com.springaidemo.common.R;
import li.com.springaidemo.pojo.Imgs;
import li.com.springaidemo.service.ImgsService;
import li.com.springaidemo.timing.AddSchedule;
import li.com.springaidemo.timing.OssTiming;
import li.com.springaidemo.timing.SchedulerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/oss")
public class OssController {

    public static OSS ossClient;
    @Value("${spring.cloud.alicloud.oss.bucket}")
    private String bucket;
    @Value("${spring.cloud.alicloud.oss.endpoint}")
    private String endpoint;
    @Value("${spring.cloud.alicloud.access-key}")
    private String accessId;
    @Autowired
    private OssTiming ossTiming;
    @Autowired
    private ImgsService imgsService;
    public OssController(OSS ossClient) {
        OssController.ossClient = ossClient;
    }

    @GetMapping("/del")
    public R del(){
        ossTiming.timingDeleteImg();
        return R.success();
    }

    @RequestMapping("/policy")
    public R policy() throws ServletException, IOException {

        // 从环境变量中获取访问凭证。运行本代码示例之前，请确保已设置环境变量OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        //EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 填写Bucket名称，例如examplebucket。
        // 填写Host名称，格式为https://bucketname.endpoint。
        String host = "https://"+bucket+"."+endpoint+"/";
        // 设置上传回调URL，即回调服务器地址，用于处理应用服务器与OSS之间的通信。OSS会在文件上传完成后，把文件上传信息通过此回调URL发送给应用服务器。
//        String callbackUrl = "https://192.168.0.0:8888";
        // 设置上传到OSS文件的前缀，可置空此项。置空后，文件将上传至Bucket的根目录下。
        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String dir = format+"/";
        Map<String, String> respMap=null;
        try {
            long expireTime = 30;
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            // PostObject请求最大可支持的文件大小为5 GB，即CONTENT_LENGTH_RANGE为5*1024*1024*1024。
            PolicyConditions policyConds = new PolicyConditions();
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, 1048576000);
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, dir);

            String postPolicy = ossClient.generatePostPolicy(expiration, policyConds);
            byte[] binaryData = postPolicy.getBytes("utf-8");
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            String postSignature = ossClient.calculatePostSignature(postPolicy);

            respMap = new LinkedHashMap<String, String>();
            respMap.put("accessid", accessId);
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", dir);
            respMap.put("host", host);
            respMap.put("expire", String.valueOf(expireEndTime / 1000));
            // respMap.put("expire", formatISO8601Date(expiration));


        } catch (Exception e) {
            // Assert.fail(e.getMessage());
            System.out.println(e.getMessage());
        } finally {

        }
        return R.success(respMap);
    }

    @PostMapping("/deleteImg")
    public R deleteImg(@RequestBody Imgs img){
        Imgs imgs = imgsService.getOne(new QueryWrapper<Imgs>().eq("url", img.getUrl()));
        if(imgs!=null){
            imgsService.remove(new QueryWrapper<Imgs>().eq("url",img.getUrl()));
        }
//        deleteImg(img.getName());\
        int length = "https://ai-chunshuyingliang.oss-cn-beijing.aliyuncs.com/".length();
        String delImg=img.getUrl().substring(length);
        System.out.println(delImg);
//        deleteImg(delImg);
        return R.success();
    }

    public void deleteImg(String name){
        try {
            ossClient.deleteObject(bucket,name);
        }catch (Exception e){
            System.out.println(e.getMessage());
        }finally {

        }
    }
}
